<template>
  <div
    class="layout-sidebar"
    v-if="showLeftMenu || isDoubleMenu"
    :class="{ 'no-border': menuList.length === 0 }"
  >
    <!-- 双列菜单（左侧） -->
    <div
      v-if="isDoubleMenu"
      class="double-menu-left"
      :style="{ background: getMenuTheme.background }"
    >
      <Logo class="logo" />
    </div>

    <!-- 左侧菜单 || 双列菜单（右侧） -->
    <!-- v-show="menuList.length > 0" -->
    <!--  -->
    <div
      class="menu-left"
      :class="`menu-left-${getMenuTheme.theme} menu-left-${
        !menuOpen ? 'close' : 'open'
      }`"
      :style="{ background: getMenuTheme.background }"
    >
      <ElScrollbar style="height: calc(100% - 10px)">
        <div class="header" :style="{ background: getMenuTheme.background }">
          <Logo v-if="!isDoubleMenu" class="logo" />

          <p
            :class="{ 'is-double-menu-name': isDoubleMenu }"
            :style="{
              color: getMenuTheme.systemNameColor,
              opacity: !menuOpen ? 0 : 1,
            }"
          >
            {{ AppConfig.systemInfo.name }}
          </p>
        </div>
      </ElScrollbar>
      <!-- :default-active="routerPath" -->
      <!-- :unique-opened="uniqueOpened" -->
      <!-- 
        注意:侧边栏本身没宽度，靠子元素撑开宽度，而子元素中也只设了菜单宽度
        优化建议: 能否将 'el-menu-' + getMenuTheme.theme 这个提供宽度的样式上升
       -->
      <ElMenu
        :class="'el-menu-' + getMenuTheme.theme"
        :collapse="!menuOpen"
        :text-color="getMenuTheme.textColor"
        :background-color="getMenuTheme.background"
        :active-text-color="getMenuTheme.textActiveColor"
        :default-openeds="defaultOpenedMenus"
        :popper-class="`menu-left-${getMenuTheme.theme}-popper`"
        :show-timeout="50"
        :hide-timeout="50"
      >
        <!-- <SidebarSubmenu
          :list="menuList"
          :isMobile="isMobileMode"
          :theme="getMenuTheme"
          @close="handleMenuClose"
        /> -->
      </ElMenu>
      <div
        class="menu-model"
        @click="toggleMenuVisibility"
        :style="{
          opacity: !menuOpen ? 0 : 1,
          transform: showMobileModal ? 'scale(1)' : 'scale(0)',
        }"
      ></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Logo from "@/layouts/components/Logo/index.vue";
import { MenuWidth, MenuTypeEnum } from "@/constants/enums/menuEnum";
import { useMenuStore } from "@/stores/modules/menu";
import { useThemeStore } from "@/stores/modules/theme";
import AppConfig from "@/config";
defineOptions({ name: "SidebarMenu" });

console.log(AppConfig.systemInfo.name);

const menuStore = useMenuStore();
const themeStore = useThemeStore();

const { getMenuTheme } = storeToRefs(themeStore);
const { menuOpen, menuType, getMenuOpenWidth, dbMenuShowText, menuList } =
  storeToRefs(menuStore);

const MOBILE_BREAKPOINT = 800;
const ANIMATION_DELAY = 350;
const MENU_CLOSE_WIDTH = MenuWidth.CLOSE;

// 组件内部状态
const defaultOpenedMenus = ref<string[]>([]);
const isMobileMode = ref(false);
const showMobileModal = ref(false);
const currentScreenWidth = ref(0);

// 菜单宽度相关
const menuopenwidth = computed(() => getMenuOpenWidth.value);
const menuclosewidth = computed(() => MENU_CLOSE_WIDTH);

//#region 菜单类型判断
/** 菜单类型判断 ?? 是否有必要四个计算属性 */
const showLeftMenu = computed(
  () =>
    menuType.value === MenuTypeEnum.Vertical ||
    menuType.value === MenuTypeEnum.Horizontal
);
const isVerticalMenu = computed(() => {
  return menuType.value === MenuTypeEnum.Vertical;
});
const isDoubleMenu = computed(() => {
  return menuType.value === MenuTypeEnum.Two_Column;
});
const isHorizontalMenu = computed(() => {
  return menuType.value === MenuTypeEnum.Horizontal;
});
const isCompositeMenu = computed(() => {
  return menuType.value === MenuTypeEnum.Composite;
});
//#endregion

/**
 * 检查是否为移动端屏幕
 */
function isMobileScreen(): boolean {
  return document.body.clientWidth < MOBILE_BREAKPOINT;
}

/**
 * 延迟隐藏移动端模态框
 */
function delayHideMobileModal(): void {
  setTimeout(() => {
    showMobileModal.value = false;
  }, ANIMATION_DELAY);
}

//#region 菜单列表
// 路由相关
// const firstLevelMenuPath = computed(() => route.matched[0]?.path);
// const routerPath = computed(() => String(route.meta.activePath || route.path));

// // 菜单数据
// const firstLevelMenus = computed(() => {
//   return useMenuStore().menuList.filter((menu) => !menu.meta.isHide);
// });

// const menuList = computed(() => {
//   const menuStore = useMenuStore();
//   const allMenus = menuStore.menuList;

//   // 如果不是顶部左侧菜单或双列菜单，直接返回完整菜单列表
//   if (!isTopLeftMenu.value && !isDualMenu.value) {
//     return allMenus;
//   }

//   // 处理 iframe 路径
//   if (isIframe(route.path)) {
//     return findIframeMenuList(route.path, allMenus);
//   }

//   // 处理一级菜单
//   if (route.meta.isFirstLevel) {
//     return [];
//   }

//   // 返回当前顶级路径对应的子菜单
//   const currentTopPath = `/${route.path.split("/")[1]}`;
//   const currentMenu = allMenus.find((menu) => menu.path === currentTopPath);
//   return currentMenu?.children ?? [];
// });
//#endregion

/**
 * 查找 iframe 对应的二级菜单列表
 */
const findIframeMenuList = (currentPath: string, menuList: any[]) => {
  // 递归查找包含当前路径的菜单项
  const hasPath = (items: any[]): boolean => {
    for (const item of items) {
      if (item.path === currentPath) {
        return true;
      }
      if (item.children && hasPath(item.children)) {
        return true;
      }
    }
    return false;
  };

  // 遍历一级菜单查找匹配的子菜单
  for (const menu of menuList) {
    if (menu.children && hasPath(menu.children)) {
      return menu.children;
    }
  }
  return [];
};

/**
 * 切换菜单显示/隐藏
 */
const toggleMenuVisibility = (): void => {
  menuStore.setMenuOpen(!menuOpen.value);

  // 移动端模态框控制逻辑
  if (isMobileScreen()) {
    if (!menuOpen.value) {
      // 菜单即将打开，立即显示模态框
      showMobileModal.value = true;
    } else {
      // 菜单即将关闭，延迟隐藏模态框确保动画完成
      delayHideMobileModal();
    }
  }
};

/**
 * 处理菜单关闭（来自子组件）
 */
const handleMenuClose = (): void => {
  if (isMobileScreen()) {
    menuStore.setMenuOpen(false);
    delayHideMobileModal();
  }
};

/**
 * 切换双列菜单模式，是否显示文字
 */
const toggleDualMenuMode = (): void => {
  menuStore.setDbMenuShowText(!dbMenuShowText.value);
};

/**
 * 处理屏幕尺寸变化
 */
const handleScreenResize = (): void => {
  // 小屏幕自动折叠菜单
  if (currentScreenWidth.value < MOBILE_BREAKPOINT) {
    menuStore.setMenuOpen(false);
    // 在小屏幕上，如果菜单关闭则隐藏模态框
    if (!menuOpen.value) {
      showMobileModal.value = false;
    }
  } else {
    // 大屏幕上始终隐藏模态框
    showMobileModal.value = false;
  }
};

/**
 * 设置窗口大小监听器
 */
const setupWindowResizeListener = (): void => {
  currentScreenWidth.value = document.body.clientWidth;
  handleScreenResize();

  window.onresize = () => {
    currentScreenWidth.value = document.body.clientWidth;
    handleScreenResize();
  };
};

/**
 * 监听菜单开关状态变化
 */
watch(
  () => menuOpen.value,
  (isMenuOpen: boolean) => {
    if (!isMobileScreen()) {
      // 大屏幕设备上，模态框始终隐藏
      showMobileModal.value = false;
    } else {
      // 小屏幕设备上，根据菜单状态控制模态框
      if (isMenuOpen) {
        // 菜单打开时立即显示模态框
        showMobileModal.value = true;
      } else {
        // 菜单关闭时延迟隐藏模态框，确保动画完成
        delayHideMobileModal();
      }
    }
  }
);

onMounted(() => {
  setupWindowResizeListener();
});
</script>
<style lang="scss" scoped>
@use "./styles/styles.scss";
</style>

<style lang="scss">
@use "./styles/theme.scss";

.layout-sidebar {
  // 展开的宽度
  .el-menu:not(.el-menu--collapse) {
    width: v-bind(menuopenwidth);
  }

  // 折叠后宽度
  .el-menu--collapse {
    width: v-bind(menuclosewidth);
  }
}
</style>
